/*
 * File: UpdateAccessToken.java Author: Robert Bittle <guywithnose@gmail.com>
 */
package servlets;

import java.io.IOException;
import java.util.GregorianCalendar;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import data.JavaCurl;
import faceBook.User;
import foxtrotbravo.Config;

/**
 * The Class signedRequest.
 */
public class UpdateAccessToken extends AuthenticationServlet
{

  private static final Logger log = Logger.getLogger(UpdateAccessToken.class
      .getName());

  /*
   * (non-Javadoc)
   * 
   * @see
   * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
   * javax.servlet.http.HttpServletResponse)
   */
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException
  {

    if (req.getParameter("accessToken") == null
        || req.getParameter("userId") == null
        || !authenticate(Long.valueOf(req.getParameter("userId")),
            req.getParameter("accessToken")))
      resp.getWriter().write(errorJson("Authentication failed."));

    log.info("Updating user: " + req.getParameter("userId"));
    log.info("Token: " + req.getParameter("accessToken"));

    if (updateUser(req.getParameter("accessToken"),
        Long.valueOf(req.getParameter("userId"))))
    {
      resp.getWriter().write(successJson());
    } else
    {
      resp.getWriter().write(errorJson("Authentication failed."));
    }
  }

  /**
   * Creates the user.
   * 
   * @param accessToken
   *          the access token
   * @param userId
   *          the user id
   * @return true, if successful
   */
  public static boolean updateUser(String accessToken, long userId)
  {

    User user = new User(userId);

    String response = JavaCurl
        .getUrl("https://graph.facebook.com/oauth/access_token?client_id="
            + Config.AppId + "&client_secret=" + Config.AppSecret
            + "&grant_type=fb_exchange_token&fb_exchange_token=" + accessToken);
    String[] parts = response.split("[=&]");

    if (parts.length < 4)
    {
      return false;
    }
    String newAccessToken = parts[1];

    GregorianCalendar now = new GregorianCalendar();

    long newTime = Long.valueOf(parts[3].trim()) * 1000 + now.getTimeInMillis();

    GregorianCalendar expireDate = new GregorianCalendar();

    expireDate.setTimeInMillis(newTime);

    user.setAccessToken(newAccessToken);
    user.setExpireTime(expireDate.getTimeInMillis());
    user.save();
    return true;

  }

}
